let http=require('http');
let mysql=require('mysql');
//let querystring=require('querystring');
http.createServer((req,res)=>{
    res.setHeader('Access-Control-Allow-Origin', '*');
    console.log(req.url);
    let connection = mysql.createConnection({
        host     : '47.97.99.197',
        user     : 'root',
        password : 'root',
        port: '3306',
        database: 'wangjun'
    });
    connection.connect();
    if(req.url==='/favicon.ico'){
        return res.end("nn");

    }else if (req.url==='/'){
        let  sql = 'SELECT * FROM websites';
        connection.query(sql,function (err, result) {
            if(err){
                console.log('[SELECT ERROR] - ',err.message);
                return;
            }
            console.log('--------------------------SELECT----------------------------');
            console.log(result);
            res.end(JSON.stringify(result));
            console.log('------------------------------------------------------------');
        });
    } else if (req.url==='/add'){
        let  addSql = 'INSERT INTO websites(Id,name,url,alexa,country) VALUES(0,?,?,?,?)';
        let  addSqlParams = ['汪骏', 'hhhhh', '23453', 'CN'];

        connection.query(addSql,addSqlParams,function (err, result) {
            if(err){
                console.log('[SELECT ERROR] - ',err.message);
                return;
            }
            console.log('--------------------------SELECT----------------------------');
            console.log(result);
            console.log('------------------------------------------------------------');
            //res.end(JSON.stringify(result))
            // for(let i =0;i<result.length;i++){
            //     console.log(result[i]);
            // }
        });
    }
    connection.end();
    //res.end("JSON.stringify(result)")
}).listen(8080,()=>{
    console.log('server is run on 127.0.0.1:8080')
});
